<template>
  <view class="container">
    <!-- 表单组件 -->
    <view class="tips" v-if="tips.length > 0">{{ tips }}</view>
    <view class="form-wrapper">
      <u-upload
          :fileList="fileList1"
          @afterRead="afterRead"
          @delete="deletePic"
          uploadIcon="plus"
          :uploadText="isPay ? '线下支付凭证':'线下合同凭证'"
          name="1"
          multiple
          :maxCount="9"
      ></u-upload>
    </view>
    <!-- 操作按钮 -->
    <view class="footer">
      <view class="btn-wrapper">
        <view :class="{ disabled }" class="btn-item btn-item-main" @click="handleSubmit()">保存</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId:0,
      isPay:false,//是否支付
      actualPrice:0,//实际支付金额
      fileList1: [],
      type:'add',//add=新增 edit=编辑
      taskList1:{
        list:[],
      },
      taskList2:{
        list:[],
      },
      // 按钮禁用
      disabled: false
    }
  },
  computed: {
    tips() {
      let tips = this.isPay ? this.taskList1.rejectReason : this.taskList2.rejectReason
      if(!tips) return ''
      return tips
    }
  },
  onLoad(options) {
    this.orderId = options.orderId;
    this.isPay = options.isPay;
    this.actualPrice = options.actualPrice;
    if(options.type){
      this.type = options.type
    }
    if(this.isPay){
      uni.setNavigationBarTitle({
        title: '支付凭证'
      })
    }else{
      uni.setNavigationBarTitle({
        title: '合同凭证'
      })
    }
    if(this.type == 'edit'){
      this.getOrderDetail()
    }
  },
  methods: {
    getOrderDetail(){
      this.$request.get('wx/order/detail', {orderId:this.orderId}).then(({data}) => {
        let taskList1 = data.taskList.find(item=>item.taskType === 1)
        this.taskList1 = taskList1
        if(taskList1 && taskList1.fileUrls && taskList1.fileUrls.indexOf('file1') > -1){
          this.taskList1.list = Object.values(JSON.parse(taskList1.fileUrls))
          console.log(this.taskList1)
          if(this.isPay){
            this.fileList1 = this.taskList1.list.map(item=>{
              return {
                url:item
              }
            })
          }
        }
        let taskList2 = data.taskList.find(item=>item.taskType === 2)
        this.taskList2 = taskList2
        if(taskList2 && taskList2.fileUrls && taskList2.fileUrls.indexOf('file1') > -1){
          this.taskList2.list= Object.values(JSON.parse(taskList2.fileUrls))
          if(!this.isPay){
            this.fileList1 = this.taskList2.list.map(item=>{
              return {
                url:item
              }
            })
          }
        }
      })
    },
    // 表单提交
    handleSubmit() {
      const app = this;
      if(app.disabled) return
      app.disabled = true
      if(app.type == 'add'){
        if(app.isPay) {
          app.prepay()
        }else{
          app.uploadSignFile()
        }
      }else{
        app.alterOfflineTask()
      }
    },
    prepay(){
      const app = this;
      if(app.fileList1.length === 0){
        app.$toast('请上传支付凭证')
        app.disabled = false
        return
      }
      let params = {
        orderId:app.orderId,
        payType: 2,
      }
      let fileUrls = {}
      app.fileList1.forEach((item,index)=>{
        fileUrls[`file${index+1}`] = item.url
      })
      params.fileUrls =JSON.stringify(fileUrls)
      app.$request.post('wx/order/prepay',params).then(r=>{
        if(app.type == 'add'){
          app.$navTo('page_work/checkout/playResult',{orderTotalPrice:app.actualPrice,orderId:app.orderId,payType:'BALANCE'})
        }else{
          app.$navTo('page_work/user/order')
        }
      }).catch(err=>{
        app.$toast(err.errmsg)
      })
    },
    //上传签署合同
    uploadSignFile(){
      const app = this;
      if(app.fileList1.length === 0){
        app.$toast('请上传合同凭证')
        app.disabled = false
        return
      }
      let params = {
        orderId:app.orderId,
      }
      let fileUrls = {}
      app.fileList1.forEach((item,index)=>{
        fileUrls[`file${index+1}`] = item.url
      })
      params.fileUrls =JSON.stringify(fileUrls)
      app.$request.post('wx/order/uploadSignFile',params).then(res=>{
        app.$navTo('page_work/user/order')
      }).catch(err=>{
        app.$toast(err.errmsg)
      }).finally(()=>{
        app.disabled = false
      })
    },
    //修改工单
    alterOfflineTask(){
      const app = this;
      let params = {
        orderId:app.orderId,
        taskType:app.isPay ? 1 : 2,
      }
      let fileUrls = {}
      app.fileList1.forEach((item,index)=>{
        fileUrls[`file${index+1}`] = item.url
      })
      params.fileUrls =JSON.stringify(fileUrls)
      app.$request.post('wx/order/alterOfflineTask',params).then(r=>{
        app.$navTo('page_work/user/order')
      }).catch(err=>{
        app.$toast(err.errmsg)
      })
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    uploadFilePromise(url) {
      const app = this;
      return new Promise((resolve, reject) => {
        app.$request.urlFileUpload('wx/storage/upload',{
          files: [{path:url}], // 必填 临时文件路径 格式: [{path: "图片地址"}]
          // data:"向服务器传递的参数", //可不填
          // name:"后台接受文件key名称", //默认 file
        }).then(res=>{
          resolve(res[0].data.url)
        }).catch(err=>{
          app.$toast(err.errmsg)
        })
      })
    },
  },
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #fff;
  .tips{
    margin: 32rpx;
    padding: 16rpx 20rpx;
    border-radius: 10rpx;
    background: #ecebeb;
    font-size: 24rpx;
    font-weight: 500;
    color: #ff4141;
  }
  .form-wrapper {
    margin: 40rpx auto 20rpx auto;
    padding: 0 32rpx;
    width: 100%;
    box-sizing: border-box;


    /deep/ .u-form-item__body__left__content__label{
      font-size: 32rpx;
      font-weight: 500;
      color: #010812;
    }
    /deep/ .u-input{
      background: #F7F7F7;
      border-radius: 8rpx;
      padding: 20rpx 32rpx !important;
      font-size: 36rpx;
      font-weight: 500;
      color: #010812;
      border-width: 0 !important;
    }
    /deep/ .u-upload__button__text{
      margin-top: 10rpx !important;
    }
  }
}


// 底部操作栏
.footer {
  margin-top: 80rpx;

  .btn-wrapper {
    height: 100%;
    // display: flex;
    // align-items: center;
    padding: 0 40rpx;
  }

  .btn-item {
    flex: 1;
    font-size: 28rpx;
    height: 86rpx;
    color: #fff;
    border-radius: 50rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .btn-item-wechat {
    background: #0ba90b;
    margin-bottom: 26rpx;
  }

  .btn-item-main {
    background: #1777FF;
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 10rpx;
    // 禁用按钮
    &.disabled {
      opacity: 0.6;
    }
  }

}
</style>